import json
import os

class SessionManager:
    def __init__(self, session_file='sessions.json'):
        self.session_file = session_file
        self.sessions = []
        self.load_sessions()

    def load_sessions(self):
        try:
            if os.path.exists(self.session_file):
                with open(self.session_file, 'r', encoding='utf-8') as f:
                    self.sessions = json.load(f)
            else:
                self.sessions = [{
                    'id': 1,
                    'name': '默认会话',
                    'msgs': [],
                    'createdAt': '2023-01-01T00:00:00.000Z'
                }]
                self.save_sessions()
        except Exception as e:
            print(f"加载会话失败: {e}")
            self.sessions = [{
                'id': 1,
                'name': '默认会话',
                'msgs': [],
                'createdAt': '2023-01-01T00:00:00.000Z'
            }]
        return self.sessions

    def save_sessions(self,sessions):
        try:
            with open(self.session_file, 'w', encoding='utf-8') as f:
                json.dump(sessions, f, ensure_ascii=False, indent=2)
            return True
        except Exception as e:
            print(f"保存会话失败: {e}")
            return False

    def get_sessions(self):
        return self.sessions

    def add_session(self, session):
        self.sessions.append(session)
        self.save_sessions()

    def delete_session(self, session_id):
        self.sessions = [s for s in self.sessions if s['id'] != session_id]
        self.save_sessions()
   
session_manager = SessionManager()
def init_session_manager(window):
    window.expose(
        session_manager.load_sessions,
        session_manager.save_sessions,
        session_manager.get_sessions,  # 暴露新方法
        session_manager.add_session,  # 暴露新方法
        session_manager.delete_session  # 暴露新方法
    )
    return session_manager